import { _decorator, Label, ProgressBar, Tween, Node } from 'cc';
import { isFullScreen, uiName, UIView } from '../../base/UIView';
import { IPreload, PreLoadRes } from './PreLoadRes';
import Cfgs from '../../configs/Cfgs';
import { Toast } from '../../components/Toast';
import UserModel from '../../data/UserModel';
import UserCtrl from '../../data/UserCtrl';
import { Dialog } from '../../components/Dialog';
import { Loading } from '../../components/Loading';
import DailyCtrl from '../../ctrl/DailyCtrl';
import TDCtrl from '../../ctrl/TDCtrl';
import ADCtrl from '../../ctrl/ADCtrl';
import { tween } from 'cc';
import HttpApi from '../../net/HttpApi';
import { EnvType, GameConfig } from '../../data/GameConfig';
import HotUpdateMgr from '../../manager/HotUpdateMgr';
import { game } from 'cc';
import NativeHelper from '../../comm/NativeHelper';
const { ccclass, property } = _decorator;

export enum ELoadingType{
    none,
    updateRes,
    updateConfig,
    LoadingAssets,//加载资源
    LoadingNet,//加载网络
}

@ccclass('UILoading')
export class UILoading extends UIView implements IPreload {
    @property(ProgressBar)
    private progressbar: ProgressBar = null;
    @property(Label)
    private lbTips: Label = null;
    @property(Label)
    private lbVersion: Label = null;
    @property(Node)
    private btnRetry: Node = null;
    private _loadingType: ELoadingType = ELoadingType.none;
    private _loadingResDone: boolean = false;
    private _loadingNetDone: boolean = false;
    private _loadingEndlessDone: boolean = false;
    private _autoLogin: boolean = false;

    private readonly LevelPercent: [number, number] = [0.0, 0.0];
    private readonly LevelEndlessPercent: [number, number] = [0, 1.0];
    // private readonly NetPercent: [number, number] = [0.8, 1.0];
    // private readonly AllPercent: [number, number] = [0.0, 1.0];

    protected onLoad(): void {
        this.uiName = 'UILoading';
    }
    public init(...args : any): void {
        PreLoadRes.Listener = this;
    }

    public onOpen(fromUI: number, args: ELoadingType): void {
        console.log('### onOpen ==> ')
        this.setProgress(0);
        // this._loadingType = args;
        // this.goToLoading();
        // this.registerEventListener(true);
        this.forConnectComplete();//因为没有服务器，所以算连接成功
        this.checkUpdate();
        if (GameConfig.envType == EnvType.Release) {
            this.lbVersion.node.active = false;
        } else {
            this.lbVersion.node.active = true;
            this.lbVersion.string = HotUpdateMgr.instance.getLocalVersion();
        }
    }

    //=========<热更相关
    private async checkUpdate() {
        // const env = GameConfig.envType == EnvType.Test ? 'test' : 'release';
        // try {
        //     let configs = await HttpApi.bundleConfig(env);
        //     console.log('### bundleConfig', configs);
        //     HotUpdateMgr.instance.setRemoteVersion(configs);
        //     if (HotUpdateMgr.instance.checkUpdate('config')) {
        //         console.log('### checkUpdate config');
        //         this.onUpdateConfigs();
        //     } else if (HotUpdateMgr.instance.checkUpdate('res')) {
        //         this.onUpdateMain();
        //     }else{
        //         this.goToLoading();
        //     }
        // } catch (error) {
        //     console.error(error);
        //     this.onUpdateFailed();
        // }
        this.goToLoading(); // 接入热跟功能时，改注释
    }
    private onUpdateConfigs(){
        this._loadingType = ELoadingType.updateConfig;
        // this.playTipsAction(ETipsType.Updating);
        this.setProgress(0);
        var handler = HotUpdateMgr.instance.doDownload('config');
        handler.onProgress = (progress: number, bundle: string) => {
            if (progress == Number.MAX_VALUE || isNaN(progress)) {
                this.setProgress(0);
            }
            this.setProgress(progress);
        }
        handler.onFailed = (msg: string, bundle: string) => {
            this.onUpdateFailed();
        }
        handler.onSuccess = (bundle: string) => {
            console.log(`${bundle} 更新完成================================`);
            if(HotUpdateMgr.instance.checkUpdate('res')){ 
                this.onUpdateMain();
            }else{
                setTimeout(game.restart, 500);
            }
        } 
    }
    private onUpdateMain(){
        this._loadingType = ELoadingType.updateRes;
        // this.playTipsAction(ETipsType.Updating);
        this.setProgress(0);
        var handler = HotUpdateMgr.instance.doDownload('res');
        handler.onProgress = (progress: number, bundle: string) => {
            if (progress == Number.MAX_VALUE || isNaN(progress)) {
                this.setProgress(0);
            }
            this.setProgress(progress);
        }
        handler.onFailed = (msg: string, bundle: string) => {
            this.onUpdateFailed();
        }
        handler.onSuccess = (bundle: string) => {
            console.log(`${bundle} 更新完成================================`);
            setTimeout(game.restart, 500);
        } 
    }
    private onUpdateFailed() {
        this.btnRetry.active = true;
        let str = 'Please connect to the internet!';
        this.lbTips.fontSize = 38;
        this.lbTips.string = str;
        this.bindButton(this.btnRetry, ()=>{
            this.btnRetry.active = false;
            // this.setProgress(0);
            // HotUpdateMgr.instance.doDownload(bundle);
            this.checkUpdate();
        }, this);
    }
    //热更相关>=========


    private setProgress(per: number) {
        per = per || 0;
        this.progressbar.progress = per;
        this.lbTips.fontSize = 42;
        this.lbTips.string = Math.round(per * 100) + '%';
    }

    // private registerEventListener(bReg: boolean) {
    //     // let fun = bReg ? "on" : "off";
    // }

    /**本次loading是展示网络连接进度 */
    private forConnect(percent: [number, number]): void {
        this.progressbar.node.active = true;
        this.setProgress(percent[0]);
        Tween.stopAllByTarget(this.progressbar);
        new Tween(this.progressbar)
            .to(0.01,{progress: this.progressbar.progress + (percent[1] - this.progressbar.progress) * 0.015})
            .repeatForever()
            .start();
    }

    private forConnectComplete(): void {
        Tween.stopAllByTarget(this.progressbar);
        this._loadingNetDone = true;
        if(this._loadingResDone && this._loadingEndlessDone){
            this.toHall();
        }
    }
    private toHall() {
        console.log('### toHall');
        return;
        Promise.all([
            Toast.init(),
            Dialog.init(),
            Loading.init(),
        ]).then(()=>{
            UserCtrl.login();
            DailyCtrl.init();
            TDCtrl.instance.init();
            ADCtrl.instance.init();
        });
    }
    public onPreLoadAssetsProgress(progress: number): void {
        this.progressbar.node.active = true;
        const percent = this.LevelPercent; //this._autoLogin ? this.ResPercent : this.AllPercent;
        this.setProgress(percent[0] + progress * percent[1]);
    }

    public onPreLoadAssetsComplete(): void {
        this._loadingResDone = true;
        if(this._loadingEndlessDone){
            this.forConnectComplete();
        }else{
            // this.forConnect(this.NetPercent);
            this.progressbar.node.active = true;
            // this.onPreLoadEndlessComplete();
            let obj = {v: 0};
            tween(obj).to(0.5, {v: 1}, {onUpdate: (target, ratio)=> {
                this.setProgress(ratio);
            },}).call(()=>{
                this.onPreLoadEndlessComplete();
            }).start();
        }
    }
    public onPreLoadEndlessProgress(progress: number): void {
        this.progressbar.node.active = true;
        const percent = this.LevelEndlessPercent; //this._autoLogin ? this.ResPercent : this.AllPercent;
        this.setProgress(percent[0] + progress * (percent[1] - percent[0]));
    }
    public onPreLoadEndlessComplete(): void {
        this._loadingEndlessDone = true;
        if(this._loadingNetDone){
            this.forConnectComplete();
        }else{
            // this.forConnect(this.NetPercent);
            // PreLoadRes.preLoadLevel();
        }
    }

    public onClose(): any {
        Tween.stopAllByTarget(this.node);
        this.unscheduleAllCallbacks();
        // this.registerEventListener(false);
    }

    /**
     * 1.loading资源 链接网络
     * 如果是自动登录  loading资源到80%，判断网络链接成功？ 有 0.3-》20 没 无线移动 链接成功后，到100% 进入大厅
     * 如果不是自动登录 到登录页   点击登录回到loading页 loading资源到80% 判断网络链接成功？ 有 0.3-》20 没 无线移动 链接成功后，到100% 进入大厅
     */
    private goToLoading() {
        Cfgs.loadAllConfig().then(()=>{
            if(this._loadingType == ELoadingType.LoadingAssets){
                this._autoLogin = this.checkAutoLogin();
                if(this._autoLogin){
                    console.log('### UILoading LoadRes auto Login')
                    this.setProgress(0);
                    PreLoadRes.preLoadLevel();
                }else{
                    console.log('### UILoading LoadRes munual Login')
                }
            }else{
                console.log('### UILoading LoadNet')
                this.setProgress(0);
                this.progressbar.node.active = false;
                UserCtrl.init();
                UserModel.loadUserData();
                PreLoadRes.preLoadLevel();
            }
        });
    }
    //自动登录判断保存的token是否为非游客
    private checkAutoLogin() {
        return true; // 目前只有游客自动登录
        // const loginType: LoginTypeID = LocalMgr.instance.getNumber('login_type', 0);
        // if (loginType != LoginTypeID.Guest) {
        //     let token = LocalMgr.instance.getString('token', '');
        //     let uid = LocalMgr.instance.getNumber('uid', 0);
        //     if (token && uid) {
        //         return true;
        //     }
        // }
        // return false;
    }

}


